package types

import (
	"database/sql/driver"
	"encoding/json"
	"time"
)

type Date time.Time

func (d *Date) MarshalJSON() ([]byte, error) {
	if d == nil {
		return json.Marshal(nil)
	}
	t := time.Time(*d).Format("2006-1-2")
	return json.Marshal(t)
}

func (d *Date) UnmarshalJSON(bt []byte) error {
	s := ""
	e := json.Unmarshal(bt, &s)
	if e != nil {
		return e
	}
	t, e := time.Parse("2006-1-2", s)
	if e != nil {
		return e
	}
	*d = Date(t)
	return nil
}
func (d *Date) Scan(src interface{}) error {
	if t, ok := src.(time.Time); ok {
		*d = Date(t)
		return nil
	}
	s := ""
	switch ss := src.(type) {
	case string:
		s = ss
	case []byte:
		s = string(ss)
	}
	if s == "" {
		d = nil
		return nil
	}
	t, e := time.Parse("2006-1-2", s)
	if e != nil {
		return e
	}
	*d = Date(t)
	return nil
}
func (p Date) Value() (driver.Value, error) {
	return driver.Value(time.Time(p)), nil
}
